package com.qingcloud.fexecutor.controller;

import cn.hutool.core.util.StrUtil;
import com.qingcloud.base.pojo.ApiResult;
import com.qingcloud.fexecutor.base.enums.ApiTypeEnum;
import com.qingcloud.fexecutor.base.handler.ApiExecuteParam;
import com.qingcloud.fexecutor.base.handler.ApiRequestParam;
import com.qingcloud.fexecutor.base.handler.ResultJsonBean;
import com.qingcloud.fexecutor.base.utils.ApiParameterUtil;
import com.qingcloud.fexecutor.pojo.ApiSqlDTO;
import com.qingcloud.fexecutor.service.ApiInvokeService;
import com.qingcloud.fexecutor.service.OpenApiService;
import com.qingcloud.fexecutor.service.WebPageResourceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Slf4j
@Api(value = "Api执行入口", tags = "Api执行入口")
@RestController
@RequestMapping("/openApi")
public class ApiRequestController {

    @Resource
    private ApiInvokeService apiInvokeService;

    @Resource
    private OpenApiService openApiService;

    @Resource
    private WebPageResourceService webPageResourceService;

    @ApiOperation(value = "页面API资源执行接口", notes = "页面API资源执行接口")
    @PostMapping("/execute")
    public ApiResult apiExecute(@RequestBody ApiExecuteParam executeParam, HttpServletRequest request, HttpServletResponse response) throws Throwable {
        //查询API执行参数
        ApiRequestParam param = webPageResourceService.apiRequestParam(executeParam);
        //参数没传脚本
        if (StrUtil.isBlank(param.getScript()) && ApiTypeEnum.DYNAMIC.code.equals(param.getType())) {
            ApiSqlDTO sqlDTO = openApiService.findSql(param.getApiId());
            if (Objects.isNull(sqlDTO)) {
                return ApiResult.fail(param.getApiId() + "动态API未找到脚本");
            }
            param.setScript(sqlDTO.getSql());
            param.setDsId(sqlDTO.getDsId());
        }
        Object ob = null;
        try {
            ob = apiInvokeService.invoke(ApiParameterUtil.replaceValue(param, executeParam.getJson()), request, response);
            if (ob instanceof ApiResult) {
                return (ApiResult) ob;
            }
            if (ob instanceof ResultJsonBean) {
                ob = ((ResultJsonBean<?>) ob).getData();
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return ApiResult.success(ob);
    }

}
